﻿using UnityEngine;
using System.Collections;

public class WallFollower : MonoBehaviour {

	Vector2 ground_normal = Vector2.up;
	float stuck_time = 0f;
	Vector3 lastpos;
	
	
	public float speed = 40f;
	public float gravity = 40f;

	// Use this for initialization
	void Start () {
	
		if(Random.Range(0,100)<50)
			speed*=-1;
	
	}
	
	// Update is called once per frame
	void FixedUpdate () {
	
		rigidbody2D.AddForce(-ground_normal * gravity);
		rigidbody2D.angularVelocity = speed*10f;//AddTorque(speed);
		
		//Debug.DrawLine(transform.position, transform.position + (Vector3)ground_normal *5);
		
		stuck_time += Time.fixedDeltaTime;
		if(stuck_time > 1f)
		{
			stuck_time = 0;
			
			if(Vector3.Distance(lastpos,transform.position)>0.25f)
			{
				lastpos=transform.position;
			}
			else
			{
				speed*=-1;
			}
		}
	
	}
	
	void OnCollisionEnter2D(Collision2D c)
	{
		if(c.gameObject.layer == LayerMask.NameToLayer("Ground"))
		{
			ground_normal = c.contacts[0].normal;
			ground_normal.Normalize();
		}
		else
			ground_normal = Vector2.up;
	}
}
